<?php

function coalesce($array) {
	$args = func_get_args();
	while (TRUE) {
		$key = next($args);
		if ($key) {
			$value = get($array, $key);
			if ($value) {
				return $value;
			}
		} else {
			return NULL;
		}
	}
}

function get($array, $key, $default = null) {
	static $special = NULL;
	$special === NULL && $special = array(
		'@user_name' => '匿名',
		'@avatar_url' => 'http://img.heshihome.com/sources/users/1452503774364033958--w_330_h_330.jpg',
	);
	if ($key[0] === '@' && isset($special[$key])) {
		return $special[$key];
	}

	if (isset($array[$key])) {
		return $array[$key];
	} elseif (strpos($key, '.')) {
		foreach (explode('.', $key) as $segment) {
			if ($segment[0] === '@' && isset($special[$segment])) {
				return $special[$key];
			}
		
			if ( ! is_array($array) || ! array_key_exists($segment, $array)) {
				return $default;
			} else {
				$array = $array[$segment];
			}
		}
		return $array;
	} else {
		return $default;
	}
}
	
function get_have($array, $key, $default = null) {

	if (isset($array[$key]) && ! empty($array[$key])) {
		return $array[$key];
	} elseif (strpos($key, '.')) {
		foreach (explode('.', $key) as $segment) {
			if ( ! is_array($array) || ! array_key_exists($segment, $array) || empty($array[$segment])) {
				return $default;
			} else {
				$array = $array[$segment];
			}
		}
		return $array;
	} else {
		return $default;
	}
}

/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut_no_tag($string, $length, $dot = '') {
	$string = strip_tags($string);

	static $charset = NULL;
	if ($charset === NULL) {
		$charset = C('DB_CHARSET');
	}

	$strlen = strlen($string);
	if ($strlen <= $length) return $string;
	// $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if (str_replace('-','',strtolower($charset)) == 'utf8') {
		$length = intval($length-strlen($dot)-$length/3);
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		// $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	return $strcut.$dot;
}

function str_cut($string, $length, $dot = '...') {
	static $charset = NULL;
	if ($charset === NULL) {
		$charset = C('DB_CHARSET');
	}

	$strlen = strlen($string);
	if ($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if (str_replace('-','',strtolower($charset)) == 'utf8') {
		$length = intval($length-strlen($dot)-$length/3);
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	return $strcut.$dot;
}

function str_limit($str,$len){
	static $charset = NULL;
	if ($charset === NULL) {
		$charset = C('DB_CHARSET');
	}
	return mb_substr($str, 0, $len, $charset);  
}
//是否是手机浏览器
function is_mobile() { 
    $user_agent = $_SERVER['HTTP_USER_AGENT']; 
    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte"); 
    $is_mobile = false; 
    foreach ($mobile_agents as $device) { 
        if (stristr($user_agent, $device)) { 
            $is_mobile = true; 
            break; 
        } 
    } 
    return $is_mobile; 
}
function is_weixin(){
	if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			return true;
	}	
	return false;
}
//获得有key的数据

function table($name){
	$model=new Model($name,null);
	/*$model->setProperty('tablePrefix','');
	$model->setProperty('trueTableName',$name);*/
	return $model;
}
/**
 * 其它版本
 * 使用方法：
 * $post_string = "app=request&version=beta";
 * request_by_other('http://facebook.cn/restServer.php',$post_string);
 */
function request_by_other($remote_server, $post_string)
{
	$context = array(
			'http' => array(
					'method' => 'POST',
					'header' => 'Content-type: application/x-www-form-urlencoded' .
					'\r\n'.'User-Agent : Jimmy\'s POST Example beta' .
					'\r\n'.'Content-length:' . strlen($post_string) + 8,
					'content' => 'mypost=' . $post_string)
	);
	$stream_context = stream_context_create($context);
	$data = file_get_contents($remote_server, false, $stream_context);
	return $data;
}
/**
 * Goofy 2011-11-30
 * getDir()去文件夹列表，getFile()去对应文件夹下面的文件列表,二者的区别在于判断有没有“.”后缀的文件，其他都一样
 */

//获取文件目录列表,该方法返回数组
function get_dir($dir) {
	$dirArray[]=NULL;
	if (false != ($handle = opendir ( $dir ))) {
		$i=0;
		while ( false !== ($file = readdir ( $handle )) ) {
			//去掉"“.”、“..”以及带“.xxx”后缀的文件
			if ($file != "." && $file != ".." && !strpos($file,".") && $file != '.DS_Store') {
				$dirArray[$i]=$file;
				$i++;
			}
		}
		//关闭句柄
		closedir ( $handle );
	}
	return $dirArray;
}

//获取文件列表
function get_file($dir) {
	$fileArray[]=NULL;
	if (false != ($handle = opendir ( $dir ))) {
		$i=0;
		while ( false !== ($file = readdir ( $handle )) ) {
			//去掉"“.”、“..”以及带“.xxx”后缀的文件
			if ($file != "." && $file != ".."&&strpos($file,".")) {
				$fileArray[$i]="./imageroot/current/".$file;
				if($i==100){
					break;
				}
				$i++;
			}
		}
		//关闭句柄
		closedir ( $handle );
	}
	return $fileArray;
}

//调用方法getDir("./dir")……
function display_dir($str) {
	if (! is_dir ( $str ))
		die ( '不是一个目录！' );
	$files = array ();
	if ($hd = opendir ( $str )) {
		while ( $file = readdir ( $hd ) ) {
			if ($file != '.' && $file != '..') {
				if (is_dir ( $str . '/' . $file )) {
					$files [$file] = displayDir ( $str . '/' . $file );
				} else {
					$files [] = $file;
				}
			}
		}
	}
	return $files;
}

/**
 * 检测字符串编码
 * @param string $str 待检测字符串
 * @param bool $type	是否严格模式
 * @return string
 */
function check_encoding( $str, $type=true )
{
	$encodeList = array(
		'UTF-8','GB2312','GBK'
	);
	return mb_detect_encoding( $str, $encodeList,$type );
}

/**
 * 截取富文本的内容
 * @param string $str	富文本内容
 * @param int $start 开始位置
 * @param int $len	截取长度
 * @return string
 */
function cut_content( $str, $start=0, $len=250 )
{
	$encoding = checkEncoding( $str );
	$str = strip_tags(htmlspecialchars_decode( $str ));
	return mb_substr( $str, $start, $len, $encoding );
}

/**
 * 计算 html 标签数量
 * @param string $html html文本内容
 * @param array $rule	对标签属性过滤 array( element=>'img', 'attribute'=>'src', 'preg'=>'正则' )
 * @return array
 */
function content_image_count( $html='', $rule = array()  )
{
	$number = 0;
	$data = array();
	$defaultPreg = '/\\s*(\'|\")?([^\'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*/';
	$element = empty( $rule['element'] ) ? 'img' : $rule['element'];
	$attribute = empty( $rule['attribute'] ) ? 'src' : $rule['attribute'];
	$preg = empty( $rule['preg'] ) ? $defaultPreg : $rule['preg'];
	$Dom = new DOMDocument();
	$Dom->loadHtml( $html );
	$DomElement = $Dom->getElementsByTagName( $element );

	foreach( $DomElement as $element )
	{
		$src = $element->getAttribute( $attribute );
		if( preg_match( $preg, $src ) )
		{
			$data[] = $src;
			$number++;
		}
	}
	return array('number'=>$number,'data'=>$data);
}
//判断字符串是否由数字组成
function is_digtal($mixed)
{
	return ( intval($mixed).''==trim($mixed) );
}

/**
 * 格式化时间戳 bug447 问答单页，回答内容时间显示修改---服务端修改
 * @param float $time		时间戳
 * @param string $format	格式
 * @return bool|string
 */
function format_time($time, $format='Y-m-d' ) {
	if (empty($time)) {
		return '很久以前';
	}
	static $pos_time = NULL;
	$pos_time === NULL && $pos_time = time();
    $t = $pos_time - $time;

    $f = array(
        86400 => '天',
        3600 => '小时',
    );

    foreach ($f as $k=>$v) {
		if ($k === 86400) {
			$c = floor($t/$k);
			if ($c > 10) {
				return date($format, $time);
			} elseif ($c != 0) {
				return $c.$v.'前';
			}
		} elseif (0 != $c = floor($t/$k)) {
            return $c.$v.'前';
        }
    }
	return '刚刚';
}

function editor(){
	$ckeditor = new \Base\CKEditor( __ROOT__.'/Public/Plug/ckeditor/' );
	print $ckeditor->editor('ckeditor.js','');
}
